import tempfile
import os

from os.path import join

from forest.registry import get_tool

def mkefidisk(bootdir, outfile, label="INSTALLER"):
    '''Make a bootable EFI disk image, placing the contents of bootdir into
    "EFI/BOOT" in the EFI system partition.'''

    workdir = tempfile.mkdtemp(prefix="mkefidisk.")
    efiboot = join(workdir,"efiboot.img")
    get_tool('image.mkdosimg')(None, efiboot, label, graft={'EFI/BOOT':bootdir})

    #TODO will this help as a getsize?
    getsize = lambda f: os.lstat(f).st_size

    partsize = getsize(efiboot) + 17408
    disksize = get_tool('image.round_to_blocks')(17408 + partsize, 512)


    #TODO no pyanaconda dependencies
    # storage setup
    #storage = pyanaconda.storage.Storage()
    #storage.config.diskImages["efiboot"] = outfile
    #storage.setupDiskImages()

    #TODO no partspec mentiones anywhere else - where is it from?
    #efi_req = partspec.PartSpec(mountpoint="/boot/efi", fstype="efi",
    #                            size=partsize)
    #storage.autoPartitionRequests = [efi_req]
    #storage.doAutoPart = True
    #platform = pyanaconda.platform.EFI(storage)
    #storage._platform = platform

    #pyanaconda.storage.partitioning._schedulePartitions(storage, [
    #pyanaconda.storage.partitioning.doPartitioning(
    #storage.doIt()

    with get_tool('image.LoopDev')(outfile, disksize) as loopdev:
        with get_tool('image.DMDev')(loopdev, disksize) as dmdev:
            with open(efiboot, "rb") as infile:
                get_tool('files.write')("/dev/mapper/%sp1" % dmdev,
                    infile.read(), mode="wb")
            get_tool('image.dm_detach')(dmdev+"p1")
